package com.aiyige.page.test;

import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiachao on 2018/2/19.
 */

public class STBUtils {

    int utcTimeMean = 0;
    List<Long> longList = new ArrayList<>();

    public interface ServerMeanValueCallback {
        void result(long meanValue);
    }
    public void getServerTime(final ServerMeanValueCallback serverMeanValueCallback) {
        utcTimeMean = 0;
        longList.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                doUtc(serverMeanValueCallback);
            }
        }).start();


    }

    private void doUtc(ServerMeanValueCallback serverMeanValueCallback) {
        try {
            URL url = null;//取得资源对象
            url = new URL("http://116.196.89.215/time.php");
            URLConnection uc = url.openConnection();//生成连接对象
            long start = System.currentTimeMillis();
            uc.connect(); //发出连接
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
            String line;
            String result = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            long serverTime = Long.parseLong(result);
            long netUsedTime = System.currentTimeMillis() - start;//网络耗时
            long differenceTime =  (serverTime + netUsedTime) - (System.currentTimeMillis());
            Log.v(" XIACHAO", utcTimeMean+"system time=" + result +" System.currentTimeMillis="+System.currentTimeMillis()+" \ndifferenceTime="+differenceTime
                    +" netUsedTime=" + netUsedTime);
            utcTimeMean++;
            longList.add(differenceTime);
            if (utcTimeMean > 30) {
                long sum = 0;
                for (long l : longList) {
                    sum += l;
                }
                long serverMeanValue = sum / longList.size();
                Log.v("XIACHAO", "serverMeanValue:" + serverMeanValue);
                utcTimeMean = 0;
                longList.clear();
                if (serverMeanValueCallback != null) {
                    serverMeanValueCallback.result(serverMeanValue);
                }
            } else {
                doUtc(serverMeanValueCallback);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
